package com.quectel.cms.controller.securitypatrol;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.vo.securitypatrol.SecurityPartrolDeviceVo;
import com.quectel.constant.core.ResourceGroupCodeConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolDeviceSubjectDto;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolSubjectDto;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolDeviceSubjectService;
import com.quectel.core.module.securitypatrol.service.SecurityPatrolSubjectService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:11
 */
@RestController
@RequestMapping("securityPatrolDeviceSubject")
@Tag(name = "SecurityPatrolDeviceSubjectController", description = "点位关联巡检项目相关api")
public class SecurityPatrolDeviceSubjectController extends BaseController {

    @DubboReference
    private SecurityPatrolDeviceSubjectService securityPatrolDeviceSubjectService;
    @DubboReference
    private DeviceService deviceService;
    @DubboReference
    private SecurityPatrolSubjectService securityPatrolSubjectService;

    @GetMapping("getDeviceBindSubjects")
    @RequirePermissions(values = "securityPatrolDeviceSubject:list")
    @Operation(summary = "根据deviceId查询关联项目")
    public Response<Page<SecurityPatrolSubjectDto>> getDeviceBindSubjects(
            @Parameter(description = "设备id") @RequestParam Long deviceId,
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize) {

        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        request.put(LambdaUtil.getFieldName(SecurityPatrolDeviceSubjectDto::getDeviceId), deviceId);
        List<SecurityPatrolSubjectDto> list = new ArrayList<>();
        int total = securityPatrolSubjectService.queryTotal(request.getParams());
        if (total > 0) {
            list = securityPatrolSubjectService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }
        Page<SecurityPatrolSubjectDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<SecurityPatrolSubjectDto>>ok().wrap(page);
    }


    @GetMapping("getBindSubjects/{id}")
    @RequirePermissions(values = "securityPatrolDeviceSubject:list")
    @Operation(summary = "根据deviceId查询关联项目")
    public Response<SecurityPatrolDeviceSubjectDto> getBindSubjects(@PathVariable Long id) {

        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        request.put(LambdaUtil.getFieldName(SecurityPatrolDeviceSubjectDto::getDeviceId), id);
        List<SecurityPatrolDeviceSubjectDto> securityPatrolDeviceSubjectDtos = new ArrayList<>();
        securityPatrolDeviceSubjectDtos = securityPatrolDeviceSubjectService.queryList(request.getParams());
        if (securityPatrolDeviceSubjectDtos.size() <= 0) {
            return Response.<SecurityPatrolDeviceSubjectDto>ok().wrap(new SecurityPatrolDeviceSubjectDto());
        } else {
            return Response.<SecurityPatrolDeviceSubjectDto>ok().wrap(securityPatrolDeviceSubjectDtos.get(0));
        }
    }

    @PostMapping("bindSubjects")
    @RequirePermissions(values = "securityPatrolDeviceSubject:edit")
    @Operation(summary = "关联检查项")
    public Response<Object> bindSubjects(@RequestParam Byte category,
                                         @RequestParam Long[] deviceIds,
                                         @RequestBody Long[] ids) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        Long deviceTypeId = deviceService.selectCacheById(deviceIds[0]).getDeviceTypeId();

        for (Long deviceId : deviceIds) {
            DeviceDto deviceDto = deviceService.selectCacheById(deviceId);
            if (!Objects.equals(deviceDto.getDeviceTypeId(), deviceTypeId)) {
                // 判断设备类型是否一致
                return Response.error("保存失败,所选设备类型不一致");
            }
        }
        // todo  存在分布式事物问题 待修改
        for (Long deviceId : deviceIds) {
            securityPatrolDeviceSubjectService.bindSubjects(deviceId, ids, category);
        }

        return Response.ok();
    }


    /**
     * 点位关联巡检项目分页列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "securityPatrolDeviceSubject:list")
    @Operation(summary = "点位关联巡检项目分页列表")
    public Response<Page<SecurityPartrolDeviceVo>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        super.fillResourceGroupCode(request.getParams(), ResourceGroupCodeConstants.PATROL_DEVICE_GROUP);
        int total = deviceService.queryTotal(request.getParams());
        List<SecurityPartrolDeviceVo> securityPartrolDeviceVos = new ArrayList<>();
        List<DeviceDto> list = null;
        if (total > 0) {
            list = deviceService.queryList(request.getParams());
            for (DeviceDto deviceDto : list) {
                Map<String, Object> params = new HashMap<>();
                StringBuilder buffer = new StringBuilder();
                params.put(LambdaUtil.getFieldName(SecurityPatrolDeviceSubjectDto::getDeviceId), deviceDto.getId());
                params.put(LambdaUtil.getFieldName(SecurityPatrolDeviceSubjectDto::getCategory), request.getParams().get("category"));
                int subjectNums = securityPatrolDeviceSubjectService.queryTotal(params);
                SecurityPartrolDeviceVo securityPartrolDeviceVo = CopyUtils.copyObj(deviceDto, SecurityPartrolDeviceVo.class);
                securityPartrolDeviceVo.setSubjectNums(subjectNums);
                if (deviceDto.getBuildingId() == null) {
                    securityPartrolDeviceVo.setAddress(buffer.toString());
                }
                if (deviceDto.getBuildingId() != null && deviceDto.getFloorId() == null) {
                    buffer.append(deviceDto.getBuilding() != null ? deviceDto.getBuilding().getName() : "");
                    securityPartrolDeviceVo.setAddress(buffer.toString());
                }
                if ((deviceDto.getBuildingId() != null && deviceDto.getFloorId() != null) && deviceDto.getRoomId() == null) {
                    buffer.append(deviceDto.getBuilding() != null ? deviceDto.getBuilding().getName() : "")
                            .append(deviceDto.getFloor() != null ? deviceDto.getFloor().getName() : "");
                    securityPartrolDeviceVo.setAddress(buffer.toString());
                }
                if (deviceDto.getBuildingId() != null && deviceDto.getFloorId() != null && deviceDto.getRoomId() != null) {
                    buffer.append(deviceDto.getBuilding() != null ? deviceDto.getBuilding().getName() : "")
                            .append(deviceDto.getFloor() != null ? deviceDto.getFloor().getName() : "")
                            .append(deviceDto.getRoom() != null ? deviceDto.getRoom().getName() : "");
                    securityPartrolDeviceVo.setAddress(buffer.toString());
                }
                securityPartrolDeviceVos.add(securityPartrolDeviceVo);
            }
        } else {
            list = new ArrayList<>();
        }

        Page<SecurityPartrolDeviceVo> page = new Page<>(request.getPageNo(), request.getPageSize(), total, securityPartrolDeviceVos);
        return Response.<Page<SecurityPartrolDeviceVo>>ok().wrap(page);
    }


    /**
     * 查询点位关联巡检项目单条记录
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "securityPatrolDeviceSubject:edit")
    @Operation(summary = "查询点位关联巡检项目单条记录")
    public Response<SecurityPatrolDeviceSubjectDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (securityPatrolDeviceSubjectService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SecurityPatrolDeviceSubjectDto securityPatrolDeviceSubjectDto = securityPatrolDeviceSubjectService.selectById(id);

        return Response.<SecurityPatrolDeviceSubjectDto>ok().wrap((securityPatrolDeviceSubjectDto));
    }

    /**
     * 查询点位关联巡检项目单条记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "securityPatrolDeviceSubject:info")
    @Operation(summary = "查询点位关联巡检项目单条记录")
    public Response<SecurityPatrolDeviceSubjectDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (securityPatrolDeviceSubjectService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        SecurityPatrolDeviceSubjectDto securityPatrolDeviceSubjectDto = securityPatrolDeviceSubjectService.selectById(id);

        return Response.<SecurityPatrolDeviceSubjectDto>ok().wrap((securityPatrolDeviceSubjectDto));
    }

    /**
     * 保存点位关联巡检项目单条记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "securityPatrolDeviceSubject:edit")
    @Operation(summary = "保存点位关联巡检项目单条记录")
    public Response<Object> save(@RequestBody @Validated SecurityPatrolDeviceSubjectDto securityPatrolDeviceSubjectDto) {

        //填充基础数据
        fillSaveCommonData(securityPatrolDeviceSubjectDto);

        securityPatrolDeviceSubjectService.save(securityPatrolDeviceSubjectDto);

        return Response.ok();
    }

    /**
     * 修改点位关联巡检项目单条记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "securityPatrolDeviceSubject:edit")
    @Operation(summary = "修改点位关联巡检项目单条记录")
    public Response<Object> update(@RequestBody @Validated SecurityPatrolDeviceSubjectDto securityPatrolDeviceSubjectDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(securityPatrolDeviceSubjectDto.getId()));
        if (securityPatrolDeviceSubjectService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(securityPatrolDeviceSubjectDto);

        securityPatrolDeviceSubjectService.updateById(securityPatrolDeviceSubjectDto);

        return Response.ok();
    }

    /**
     * 批量删除点位关联巡检项目单条记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "securityPatrolDeviceSubject:delete")
    @Operation(summary = "批量删除点位关联巡检项目单条记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (securityPatrolDeviceSubjectService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        securityPatrolDeviceSubjectService.deleteBatch(ids);

        return Response.ok();
    }
}
